package com.qc31.monitorlib.ui.alarms

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.qc31.baselib.base.LazyLoadSirFragment
import com.qc31.baselib.loadsie.EmptyCallback
import com.qc31.baselib.rx.queryThrottle
import com.qc31.baselib.utils.loadVideoImg
import com.qc31.baselib.utils.startActivityTo
import com.qc31.comlib.entity.AlarmMedia
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.FragmentAlarmVideoPhotoBinding
import com.qc31.monitorlib.ui.LocationDialogActivity
import com.qc31.monitorlib.ui.adapter.MediaAdapter
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.utils.OrientationUtils

/** @Author Jasper @Time 2020/12/1 @Desc */
class AlarmVideoFragment :
    LazyLoadSirFragment<FragmentAlarmVideoPhotoBinding>(FragmentAlarmVideoPhotoBinding::inflate) {
    private var mOrientationUtils: OrientationUtils? = null
    private val mAdapter by lazy { MediaAdapter() }
    private var lat: Double = 0.0
    private var lng: Double = 0.0


    private var isPlay = false

    private var isPause = false

    override fun initView(view: View) {
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
        mOrientationUtils = OrientationUtils(requireActivity(), binding.mControlVideo)
        //初始化不打开外部的旋转
        mOrientationUtils?.isEnable = false
        //增加title
        binding.mControlVideo.titleTextView.visibility = View.GONE
        //设置返回键
        binding.mControlVideo.backButton.visibility = View.GONE
        //设置返回按键功能
        binding.mControlVideo.backButton.setOnClickListener { onBackPressed() }
        binding.mControlVideo.setVideoAllCallBack(callback)


        binding.mControlVideo.fullscreenButton.setOnClickListener {
            mOrientationUtils?.resolveByClick()
            binding.mControlVideo.startWindowFullscreen(
                requireContext(),
                actionBar = true,
                statusBar = true
            )
        }
        binding.mControlVideo.initVoice()
        binding.mControlVideo.postDelayed({ binding.mControlVideo.hiedView() }, 500)

        binding.mControlVideo.run {
            isRotateViewAuto = true
            isLockLand = true
            isShowFullAnimation = true
            setIsTouchWigetFull(false)
            playTag = "ALARM"


        }


        binding.includeRecycler.recyclerView.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        binding.includeRecycler.recyclerView.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val entity = mAdapter.data[position]
            mAdapter.index = position
            mAdapter.notifyDataSetChanged()
            binding.ivAlarmMedia.loadVideoImg(requireContext(), entity.fullLink, 1000)
        }


    }

    override fun initData() {}

    override fun initEvent() {
        binding.tvAlarmAddress.queryThrottle().autoDispose(scopeProvider).subscribe {
            startActivityTo<LocationDialogActivity>(requireContext()) {
                putExtra("lat", lat)
                putExtra("lng", lng)
            }
        }
    }

    fun setVideoData(
        data: MutableList<AlarmMedia.MediaInfo>,
        entity: AlarmMedia.MediaInfo
    ) {
        if (data.isEmpty()) {
            loadService.showCallback(EmptyCallback::class.java)
            return
        }
        loadService.showSuccess()
        setVideoDesc(entity)
        mAdapter.index = 0
        mAdapter.setList(data)
        lat = entity.glat.toDouble()
        lng = entity.glng.toDouble()
    }


    @SuppressLint("SetTextI18n")
    fun setVideoDesc(entity: AlarmMedia.MediaInfo) {
        binding.mControlVideo.visibility = View.VISIBLE
        binding.mControlVideo.release()
        binding.mControlVideo.setUp(entity.fullLink, false, entity.time)
        binding.lrTvAlarmTime.setRightText(entity.time)
        binding.lrTvAlarmSpeed.setRightText("${entity.speed} ${getString(R.string.unit_speed)}")

        binding.lrTvAlarmReason.setRightText(entity.reason)
        binding.tvAlarmAddress.text = entity.addr
        binding.ivAlarmMedia.loadVideoImg(requireContext(), entity.fullLink, 1000)
    }

    fun onBackPressed(): Boolean {

        // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
        // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
        if (mOrientationUtils != null) {
            mOrientationUtils?.backToProtVideo()
        }
        return GSYVideoManager.backFromWindowFull(requireActivity())


    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
        mOrientationUtils?.setIsPause(true)
        isPause = true
    }

    override fun onResume() {
        super.onResume()
        mOrientationUtils?.setIsPause(false)
        isPause = false
        GSYVideoManager.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        mOrientationUtils?.releaseListener()

    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            binding.mControlVideo.onConfigurationChanged(
                requireActivity(),
                newConfig,
                mOrientationUtils,
                true,
                true
            )
        }
    }

    private val callback = object : GSYSampleCallBack() {
        override fun onPrepared(url: String?, vararg objects: Any?) {
            super.onPrepared(url, *objects)
            isPlay = true
        }

        override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
            super.onQuitFullscreen(url, *objects)
            mOrientationUtils?.backToProtVideo()
        }
    }


}